#pragma once
#include <string>
#include <vector>
#include <iostream>
#include <pthread.h>
#include <semaphore.h>

template <class T>
class RingQuene
{
private:
    void P(sem_t& s)
    {
        sem_wait(&s);
    }

    void V(sem_t& s)
    {
        sem_post(&s);
    }
public:
    RingQuene(int max_cap)
        : _ringqueue(max_cap), _max_cap(max_cap), _c_step(0), _p_step(0)
    {
        sem_init(&_data_sem,0,0);
        sem_init(&_space_sem,0,max_cap);

        pthread_mutex_init(&_p_mutex,nullptr);
        pthread_mutex_init(&_c_mutex,nullptr);
    }

    void Push(const T& in) // 生产者
    {
        P(_space_sem);
        pthread_mutex_lock(&_p_mutex);
        
        _ringqueue[_p_step] = in;
        _p_step++;
        _p_step %= _max_cap;
        V(_data_sem);
        pthread_mutex_unlock(&_p_mutex);
    }

    void Pop(T* out) //消费者
    {
        P(_data_sem);
        pthread_mutex_lock(&_c_mutex);
        
        *out = _ringqueue[_c_step];
        _c_step++;
        _c_step %= _max_cap;
        V(_space_sem);
        pthread_mutex_unlock(&_c_mutex);
    }

    ~RingQuene()
    {
        sem_destroy(&_data_sem);
        sem_destroy(&_space_sem);

        pthread_mutex_destroy(&_p_mutex);
        pthread_mutex_destroy(&_c_mutex);
    }

private:
    std::vector<T> _ringqueue;
    int _max_cap;

    int _c_step; //消费者的位置
    int _p_step; //生产者的位置

    sem_t _data_sem; //消费者关心的信号量
    sem_t _space_sem; //生产者关心的信号量

    pthread_mutex_t _c_mutex;
    pthread_mutex_t _p_mutex;
};